package org.bycloud.web.auth;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.bycloud.common.Captcha;
import org.bycloud.common.Constants;
import org.bycloud.common.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
public class LoginController {

	@GetMapping("/login")
	public String login() {
		return "login";
	}

	@PostMapping("/login")
	@ResponseBody
	public Result loginFail(HttpServletRequest request) {
		String exception = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
		if (StringUtils.isBlank(exception)) {
			return Result.writeSuccessData("/index");
		}
		return Result.failure("登录失败 : " + exception);
	}

	@RequestMapping("/success")
	@ResponseBody
	public Result success() {
		return Result.writeSuccessData("/index");
	}

	@RequestMapping({ "/", "/index" })
	public String index() {
		return "index";
	}

	@RequestMapping("/captcha")
	public void captcha(HttpServletResponse response, HttpSession session) {
		try {
			Captcha captcha = new Captcha(98, 30);
			session.setAttribute(Constants.CAPTCHA, captcha.getCode());
			captcha.write(response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
